﻿using InfonavaEye.common;
using InfonavaEye.handler;
using InfonavaEye.Handler;
using InfonavaEye.model;
using Sylan.Common.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace InfonavaEye.Forms
{
    public partial class ManualCaptureForm : Form
    {
        /// <summary>
        /// 当前抓拍的图像路径
        /// </summary>
        private string currentImagePath = null;

        private bool captureTimerStoped = false;

        /// <summary>
        /// 形状 1 线型，2 圆型
        /// </summary>
        private int shape = 1;

        /// <summary>
        /// 读取抓拍按钮状态-定时器
        /// </summary>
        private System.Timers.Timer captureTimer;

        private CameraHandler cameraHandler = CameraHandler.Instance;

        private PLCHandler plcHandler = PLCHandler.Instance;

        public ManualCaptureForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false; //加载时 取消跨线程检查
            this.WindowState = FormWindowState.Maximized;
        }

        private void ManualCaptureForm_Load(object sender, EventArgs e)
        {
            FormDataBridge.ClearData();
            this.cameraHandler.IncreaseCurrentFileBatchNum();

            drawingBox.Height = (int)( drawingBox.Width * 2048/ 3072);
            drawingBox.Refresh();
            capturePictureBox.Height = (int)(capturePictureBox.Width * 2048 / 3072 );
            capturePictureBox.Refresh();

            FormDataBridge.receiveOCRResult += receiveOCRResult;
            FormDataBridge.appendResultDelegate += FormDataBridge_appendResultDelegate;

            #region OCR识别结果
            this.loadingPictureBox.Image = Properties.Resources.loading;
            this.loadingPictureBox.Visible = false;
            this.lblCode.Text = "";
            this.lblCode.Text = "暂无结果";
            this.lblCode.Visible = true;
            this.lblLoading.Visible = false;
            this.lblResult1.Visible = true;
            #endregion

            this.startDevice();
        }

        private void ManualCaptureForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.stopDevice();
            /* formAutoSize.afterSizeChangeDelegate -= afterSizeChangeDelegate;
            formAutoSize.beforeSizeChangeDelegate -= beforeSizeChangeDelegate;*/
            FormDataBridge.receiveOCRResult -= receiveOCRResult;
            FormDataBridge.appendResultDelegate -= FormDataBridge_appendResultDelegate;
        }

        /// <summary>
        /// 开启各种设备
        /// </summary>
        private void startDevice(bool openCamera = true, bool openPlC = true)
        {
            ThreadHelper.ExcuteThreadTask(() =>
            {
                if (openPlC)
                {
                    initCaptureTimer();
                    plcHandler.PLCInitCompleteDelegate += CameraHandler_PLCInitCompleteDelegate;
                    plcHandler.StartPLC();
                }

                if (openCamera)
                {
                    cameraHandler.captureImageDelegate += CaptureImage;
                    cameraHandler.initCompleteDelegate += CameraHandler_initCompleteDelegate;
                    cameraHandler.play(this.drawingBox);
                }

            }, 50);
        }

        private void CameraHandler_PLCInitCompleteDelegate()
        {
           /* if (this.btnCapture.InvokeRequired)//如果调用控件的线程和创建创建控件的线程不是同一个则为True
            {
                if (this.btnCapture.IsHandleCreated)
                {
                    this.btnCapture.Visible = true;
                }
            }*/
            captureTimer.Start();
            //int[] xyz = plcHandler.readCurrentXYZ();
            
            //防止在其他地方初始化后 频繁调用这里
            plcHandler.PLCInitCompleteDelegate -= CameraHandler_PLCInitCompleteDelegate;
        }

        private void initCaptureTimer()
        {
            captureTimerStoped = false;
            captureTimer = new System.Timers.Timer();
            captureTimer.Interval = 80;
            //captureTimer.Enabled = true;
            captureTimer.AutoReset = false;
            captureTimer.Elapsed += new ElapsedEventHandler(Capture_Elapsed);
        }

        private void stopDevice(bool closeCamera = true, bool closePlC = true)
        {
            if (closeCamera)
            {
                cameraHandler.captureImageDelegate -= CaptureImage;
                cameraHandler.initCompleteDelegate -= CameraHandler_initCompleteDelegate;
            }

            if (closePlC)
            {
                if (captureTimer != null)
                {
                    captureTimerStoped = true;
                    captureTimer.Stop();
                }
                plcHandler.PLCInitCompleteDelegate -= CameraHandler_PLCInitCompleteDelegate;
            }
        }

        private void receiveOCRResult(OCRResult result)
        {
            this.Invoke(new Action(() =>
            {
                this.lblLoading.Visible = false;
                this.loadingPictureBox.Visible = false;
                this.lblCode.Visible = true;
                this.lblResult1.Visible = true;
                if (result.filePath.Equals(currentImagePath))
                {
                    this.lblCode.Text = result.code;
                }
                else
                {
                    this.lblCode.Text = "";
                }

            }));
        }
        private void FormDataBridge_appendResultDelegate(OCRResult result)
        {
            
        }

        /// <summary>
        /// 抓拍
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Capture_Elapsed(object sender, EventArgs e)
        {
            try
            {
                captureTimer.Stop();
                if (plcHandler.checkCapturePressed())
                {
                    if (CameraHandler.captureing)
                    {
                        //MessageBox.Show("正在抓拍，请不要重复按抓拍按钮");
                        Console.WriteLine("正在抓拍，请不要重复按抓拍按钮");
                        return;
                    }

                    CameraHandler.captureing = true;
                    //TODO 调用相机的抓拍
                    cameraHandler.StartCapture();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("抓拍，发生异常：" + ex.StackTrace);
                MessageBox.Show("抓拍发生异常，请找管理员");
            }
            finally
            {
                if (!captureTimerStoped)
                {
                    captureTimer.Start();
                }
                //captureing = false;
            }
        }

        private void CaptureImage(string imagePath)
        {
            this.Invoke(new Action(() =>
            {
                currentImagePath = imagePath;
                this.capturePictureBox.Load(imagePath);
                if (this.shape == 1)
                {
                    this.lblCode.Text = "";
                    this.lblCode.Visible = false;
                    this.lblLoading.Visible = true;
                    this.loadingPictureBox.Visible = true;
                }

                FormDataBridge.appendOCRTask(imagePath, shape, cbSample.Checked);
            }));
        }

        private void CameraHandler_initCompleteDelegate()
        {
           
        }

        private void radioShape1_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton uc = sender as RadioButton;

            if (uc.Tag.ToString().Equals("2"))
            {
                this.shape = 2;
            }
            else {
                this.shape = 1;
            }
        }

        private void btnCapture_Click(object sender, EventArgs e)
        {
            //删除旧数据
            //FormDataBridge.removeOCRResult(currentImagePath);

            if (capturePictureBox.Image != null)
            {
                Graphics g = Graphics.FromImage(capturePictureBox.Image);
                g.Clear(Color.White);
                g.Dispose();
                capturePictureBox.Refresh();
                this.lblCode.Text = "";
            }

            //测试
            /* var basePath = "D:\\project\\code\\infynova-eye-desk\\InfonavaEye\\bin\\x64\\Debug\\Image\\2022-09-09\\1";
             var filePath = basePath + "\\160921_7.jpg";
             var newPath = basePath + "\\" + DateTime.Now.Ticks + ".jpg";
             File.Copy(filePath, newPath, true);
             this.CaptureImage(newPath);*/
            this.cameraHandler.StartCapture();
        }

        private void btnViewList_Click(object sender, EventArgs e)
        {
            this.cameraHandler.pause();//暂停视频
            ListForm form = new ListForm();
            form.ListCloseDelegate += () =>
            {
                this.cameraHandler.play(this.drawingBox);//重新显示视频
            };
            form.clearListDelegate += () =>
            {
                //ListForm清除了数据，就需要增加新文件夹
                this.cameraHandler.IncreaseCurrentFileBatchNum();
            };
            form.Show();
        }

        private void linkDir_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string filePath = CameraHandler.CurrentBatchDir;
            if (String.IsNullOrEmpty(filePath))
            {
                MessageBox.Show("未找到任何文件夹，请先拍照");
                return;
            }
            util.FileHelper.openDir(filePath);
        }

        private void btnRefreshPic_Click(object sender, EventArgs e)
        {

            ThreadHelper.ExcuteThreadTask(() =>
            {
                this.cameraHandler.play(this.drawingBox);
            });
        }

        private void drawingBox_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            GraphicsHelper.SetGDIHigh(g);
            Color bgColor = Color.FromArgb(255, 233, 233, 233);
            GraphicsHelper.FillRoundRectangle(e.ClipRectangle, g, 15, bgColor);
        }
    }
}
